package org.whatever.aha.zjut.platform.service.project;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.entity.project.ProjectResource;
import org.whatever.aha.zjut.platform.mapper.project.ProjectResourceMapper;
import org.whatever.aha.zjut.platform.service.TencentCosService;
import org.whatever.aha.zjut.platform.vo.CosPolicyVo;
import org.whatever.aha.zjut.platform.vo.CosPostPolicyVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectResourceVo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Vc
 * @version 1.0
 * @Desc
 * @date 2021/09/15 0:04
 */
@RequiredArgsConstructor
@Service
public class ProjectResourceService {
    final ProjectResourceMapper projectResourceMapper;
    final TencentCosService tencentCosService;
    final ProjectService projectService;

    /**
     * 新增项目资源
     *
     * @param projectId
     * @param resourceName
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    public Integer addProjectResource(int projectId, int stageId, String cosPath, String resourceName) {
        //插入数据库
        ProjectResource projectResource = new ProjectResource();
        projectResource.setProjectId(projectId);
        projectResource.setStageId(stageId);
        projectResource.setCosPath(cosPath);
        projectResource.setProjectResourceName(resourceName);

        return projectResourceMapper.insert(projectResource);
    }

    /**
     * 获得资源上传链接
     *
     * @param projectId
     * @param resourceName
     * @return
     */
    public CosPolicyVo getSign(int projectId, int stageId, String resourceName){
        //生成cos的路径
        int userId = StpUtil.getLoginIdAsInt();
        String fileName = "/user_files/" + userId + "/" + projectId + "/" + stageId + "/" + resourceName;
        return tencentCosService.signPut(fileName);
    }

    /**
     * 新增项目资源with bucket
     *
     * @param projectId
     * @param stageId
     * @param resourceName
     * @return
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    public CosPostPolicyVo addProjectResourceWithBucket(int projectId, int stageId, String resourceName) {
        //生成cos的路径
        int userId = StpUtil.getLoginIdAsInt();
        String fileName = "/user_files/" + userId + "/" + projectId + "/" + stageId + "/" + resourceName;
        CosPostPolicyVo cosPostPolicyVo = tencentCosService.signPostAuthorization(fileName);
        //插入数据库
        ProjectResource projectResource = new ProjectResource();
        projectResource.setProjectId(projectId);
        projectResource.setCosPath(fileName);
        projectResource.setProjectResourceName(resourceName);
        projectResourceMapper.insert(projectResource);

        return cosPostPolicyVo;
    }


    /**
     * 更新项目资源
     *
     * @param projectResourceId
     * @param projectResourceName
     * @param cosPath
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    public CosPolicyVo updateProjectResourceById(int projectResourceId, String projectResourceName, String cosPath) {
//        tencentCosService.deleteCos(cosPath);
        ProjectResource projectResourcePre = projectResourceMapper.selectById(projectResourceId);
        int userId = StpUtil.getLoginIdAsInt();
        String fileName = "/user_files/" + userId + "/" + projectResourcePre.getProjectId() + "/" + projectResourcePre.getStageId() + "/" + projectResourceName;
        CosPolicyVo cosPolicyVo = tencentCosService.signPut(fileName);

        ProjectResource projectResource = new ProjectResource();
        projectResource.setProjectResourceId(projectResourceId);
        projectResource.setCosPath(cosPath);
        projectResource.setProjectResourceName(projectResourceName);
        projectResourceMapper.update(projectResource, new UpdateWrapper<ProjectResource>().eq("project_resource_id",projectResourceId));
        return cosPolicyVo;
    }

    /**
     * 根据项目资源id获取项目资源下载链接
     *
     * @param projectResourceId 项目资源id
     * @return 项目资源
     */
    public CosPolicyVo getDownloadById(int projectResourceId) {
        ProjectResource projectResource = projectResourceMapper.selectById(projectResourceId);
        if (projectResource == null) {
            throw new AppException(ErrorCode.RESOURCE_NOT_EXIST);
        }
        return tencentCosService.signDownload(projectResource.getCosPath());
    }


    public ProjectResource getProjectResourceById(int projectResourceId) {
        ProjectResource projectResource = projectResourceMapper.selectById(projectResourceId);
        if (projectResource == null) {
            throw new AppException(ErrorCode.RESOURCE_NOT_EXIST);
        }
        return projectResource;
    }

    /**
     * 根据项目资源id删除项目资源
     *
     * @param projectResourceId 项目资源id
     * @return 删除条数
     */
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    public int deleteProjectResourceById(int projectResourceId) {
        ProjectResource projectResource = projectResourceMapper.selectById(projectResourceId);
        if (projectResource == null) {
            throw new AppException(ErrorCode.RESOURCE_NOT_EXIST);
        }
        if(StpUtil.getLoginIdAsInt() != (int)projectService.getLeaderId(projectResource.getProjectId())){
            throw new AppException(ErrorCode.OPERATION_NOT_AUTHORIZED);
        }
        //不直接删除资源，只删除记录
        //tencentCosService.deleteCos(projectResource.getCosPath());
        return projectResourceMapper.deleteById(projectResourceId);
    }

    /**
     * 根据stageId获得此项目ID所有的资源信息
     *
     * @param projectId
     * @param stageId
     * @return
     */
    public List<ProjectResourceVo> getAllProjectResourceByProjectId(int projectId, int stageId) {
        List<ProjectResourceVo> prvs = new ArrayList<>();
        List<ProjectResource> prs = projectResourceMapper.selectList(new QueryWrapper<ProjectResource>().eq("project_id", projectId).eq("stage_id",stageId));
        prs.forEach(pr->{
            ProjectResourceVo prv = new ProjectResourceVo();
            BeanUtils.copyProperties(pr,prv);
            prv.setCosPolicyVo(tencentCosService.signDownload(pr.getCosPath()));
            prvs.add(prv);
        });
        return prvs;
    }


}
